<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />





  <link rel="alternate" href="/atom.xml" title="结网之路" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="本章主要讲了如何使用 SQLite 进行持久化存储，包含了 CRUD 四个操作，使用基础的 SQLiteOpenHelper 与 Cursor 构造程序
GitHub 地址：完成14章所有内容



为什么要用数据库而不是文本文件来存储数据呢？因为如果用普通的文本文件（比如 txt）存储数据，每次读取时都要读取整个文件的内容，完成修改后再全部保存，一旦数据量较大，将十分耗费时间和资源。

SQL">
<meta property="og:type" content="article">
<meta property="og:title" content="Android编程权威指南（第二版）学习笔记（十四）—— 第14章 SQLite 数据库">
<meta property="og:url" content="https://kniost.github.io/2017-01-09-cj0ajvouy000y1js6vgfqoi6s/index.html">
<meta property="og:site_name" content="结网之路">
<meta property="og:description" content="本章主要讲了如何使用 SQLite 进行持久化存储，包含了 CRUD 四个操作，使用基础的 SQLiteOpenHelper 与 Cursor 构造程序
GitHub 地址：完成14章所有内容



为什么要用数据库而不是文本文件来存储数据呢？因为如果用普通的文本文件（比如 txt）存储数据，每次读取时都要读取整个文件的内容，完成修改后再全部保存，一旦数据量较大，将十分耗费时间和资源。

SQL">
<meta property="og:updated_time" content="2017-03-14T06:43:07.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android编程权威指南（第二版）学习笔记（十四）—— 第14章 SQLite 数据库">
<meta name="twitter:description" content="本章主要讲了如何使用 SQLite 进行持久化存储，包含了 CRUD 四个操作，使用基础的 SQLiteOpenHelper 与 Cursor 构造程序
GitHub 地址：完成14章所有内容



为什么要用数据库而不是文本文件来存储数据呢？因为如果用普通的文本文件（比如 txt）存储数据，每次读取时都要读取整个文件的内容，完成修改后再全部保存，一旦数据量较大，将十分耗费时间和资源。

SQL">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://kniost.github.io/2017-01-09-cj0ajvouy000y1js6vgfqoi6s/"/>





  <title> Android编程权威指南（第二版）学习笔记（十四）—— 第14章 SQLite 数据库 | 结网之路 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">结网之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">临渊羡鱼，不如退而结网</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://kniost.github.io/2017-01-09-cj0ajvouy000y1js6vgfqoi6s/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="kniost">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="结网之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android编程权威指南（第二版）学习笔记（十四）—— 第14章 SQLite 数据库
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-01-09T10:54:10+08:00">
                2017-01-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android编程权威指南学习笔记/" itemprop="url" rel="index">
                    <span itemprop="name">Android编程权威指南学习笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017-01-09-cj0ajvouy000y1js6vgfqoi6s/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017-01-09-cj0ajvouy000y1js6vgfqoi6s/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本章主要讲了如何使用 SQLite 进行持久化存储，包含了 CRUD 四个操作，使用基础的 SQLiteOpenHelper 与 Cursor 构造程序</p>
<p>GitHub 地址：<br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/2927544a20495b24a5c834b447af8b6afc2723e9" target="_blank" rel="external">完成14章所有内容</a></p>
</blockquote>
<hr>
<blockquote>
<p><strong>为什么要用数据库而不是文本文件来存储数据呢？</strong><br>因为如果用普通的文本文件（比如 txt）存储数据，每次读取时都要读取整个文件的内容，完成修改后再全部保存，一旦数据量较大，将十分耗费时间和资源。</p>
</blockquote>
<p>SQLite是类似于MySQL的开源关系型数据库。不同于其他数据库的是,SQLite使用单个文件存储数据,使用SQLite库读取数据。Android标准库包含SQLite库以及配套的一些Java辅助类。</p>
<h1 id="1-定义-Schema（架构）"><a href="#1-定义-Schema（架构）" class="headerlink" title="1. 定义 Schema（架构）"></a>1. 定义 Schema（架构）</h1><p>本应用需要保存的应该是一个 Crime 的全部数据，比如一个表格可以下表这样。</p>
<table>
<thead>
<tr>
<th style="text-align:center">_id</th>
<th style="text-align:center">uuid</th>
<th style="text-align:center">title</th>
<th style="text-align:center">date</th>
<th style="text-align:center">solved</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">1</td>
<td style="text-align:center">13090624138324</td>
<td style="text-align:center">Stolen yougurt</td>
<td style="text-align:center">13090636733242</td>
<td style="text-align:center">0</td>
</tr>
<tr>
<td style="text-align:center">2</td>
<td style="text-align:center">13090274859392</td>
<td style="text-align:center">Dirty sink</td>
<td style="text-align:center">13090732131909</td>
<td style="text-align:center">1</td>
</tr>
</tbody>
</table>
<blockquote>
<p>程序员的一个目标，或者说信条，就是“不要重复造轮子”，也就是说，多花时间思考复用代码的编写和调用，避免在应用中到处使用重复代码。<br>基于上述准则，我们可以使用能统一定义模型层对象的高级 ORM（对象关系映射）工具，不过对于本章代码来说，因为需要掌握更加基础的内容，将会自己实现数据库操作。</p>
</blockquote>
<p>首先创建一个 Package，名为 database， 然后定义数据架构类 CrimeDbSchema.java </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// CrimeDbSchema.java</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CrimeDbSchema</span> </span>&#123;</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">CrimeTable</span> </span>&#123;</div><div class="line">        <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String NAME = <span class="string">"crimes"</span>;</div><div class="line"></div><div class="line">        <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Cols</span> </span>&#123;</div><div class="line">            <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String UUID = <span class="string">"uuid"</span>;</div><div class="line">            <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String TITLE = <span class="string">"title"</span>;</div><div class="line">            <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String DATE = <span class="string">"date"</span>;</div><div class="line">            <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String SOLVED = <span class="string">"solved"</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>这里有一个小 Tip，Android Studio 中有输入一长串前缀的 Live Template，比如要输入<code>public static final String</code>，只需要打 psfs 即可。</p>
</blockquote>
<h1 id="2-初始创建数据库"><a href="#2-初始创建数据库" class="headerlink" title="2. 初始创建数据库"></a>2. 初始创建数据库</h1><p>一般来说，在实际开发中，打开一个数据库之前，由于不知道其是否存在，是否有更新，所以要经过如下步骤：</p>
<ol>
<li>确认目标数据库是否存在。</li>
<li>如果不存在，首先创建数据库，然后创建数据库表以及必需的初始化数据。</li>
<li>如果存在，打开并确认数据库架构是否为最新版本</li>
<li>如果是旧版，就运行相关代码升级到最新版本</li>
</ol>
<p>在 Android 中，提供了一个<code>SQLiteOpenHelper</code>类用于处理这些打开数据库时繁杂的工作。我们可以创建一个<code>SQLiteOpenHelper</code>的子类用于对自己的数据库进行处理，比如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CrimeBaseHelper</span> <span class="keyword">extends</span> <span class="title">SQLiteOpenHelper</span> </span>&#123;</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> VERSION = <span class="number">1</span>;</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String DATABASE_NAME = <span class="string">"crimeBase.db"</span>;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CrimeBaseHelper</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, DATABASE_NAME, <span class="keyword">null</span>, VERSION);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">	<span class="comment">// 如果数据库不存在，就调用该函数创建一个数据库</span></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(SQLiteDatabase db)</span> </span>&#123;</div><div class="line">    	 <span class="comment">// 一定要注意语句之间的空格，因为语句是一个字符串</span></div><div class="line">    	 <span class="comment">// 如果没有空格，对于 SQL 来说，就是无意义的语句</span></div><div class="line">    	 <span class="comment">// 比如下面的 table 后面一定要接一个空格</span></div><div class="line">        db.execSQL(<span class="string">"create table "</span> + CrimeTable.NAME + <span class="string">"("</span> +</div><div class="line">                <span class="string">" _id integer primary key autoincrement, "</span> +</div><div class="line">                CrimeTable.Cols.UUID + <span class="string">", "</span> +</div><div class="line">                CrimeTable.Cols.TITLE + <span class="string">", "</span> +</div><div class="line">                CrimeTable.Cols.DATE + <span class="string">", "</span> +</div><div class="line">                CrimeTable.Cols.SOLVED +</div><div class="line">                <span class="string">")"</span></div><div class="line">        );</div><div class="line">    &#125;</div><div class="line"></div><div class="line">	<span class="comment">// 如果版本升级了，就调用 onUpgrade() 函数</span></div><div class="line">	<span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onUpgrade</span><span class="params">(SQLiteDatabase db, <span class="keyword">int</span> oldVersion, <span class="keyword">int</span> newVersion)</span> </span>&#123;</div><div class="line"></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>由于数据库结构调整太麻烦，在实际开发中最好的做法应该是直接删除数据库文件（最方便的就是卸载程序） :)</p>
</blockquote>
<h1 id="3-打开数据库"><a href="#3-打开数据库" class="headerlink" title="3. 打开数据库"></a>3. 打开数据库</h1><p>然后在 Model 层（在这里是 CrimeLab 单例）中打开数据库</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mContext = context.getApplicationContext();</div><div class="line">mDataBase = <span class="keyword">new</span> CrimeBaseHelper(mContext)</div><div class="line">		.getWritableDatabase();</div></pre></td></tr></table></figure>
<h1 id="4-写入数据库（插入与更新）"><a href="#4-写入数据库（插入与更新）" class="headerlink" title="4. 写入数据库（插入与更新）"></a>4. 写入数据库（插入与更新）</h1><h2 id="4-1-使用-ContentValues"><a href="#4-1-使用-ContentValues" class="headerlink" title="4.1 使用 ContentValues"></a>4.1 使用 ContentValues</h2><p>负责处理数据库写入和更新操作的辅助类是 ContentValues 类。它是个键值存储类，类似于 Java 的 HashMap（查看源码可以发现它就是一个 HashMap）和前面用过的 Bundle。不同的是, ContentValues 专门用于处理SQLite数据。我们需要一个 Model 层的方法，把 Model 层数据转换为ContentValues，由于在 Model 层外，对数据的操作应该只有对 Model 对象的操作，所以这个方法应该是私有的。示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> ContentValues <span class="title">getContentValues</span><span class="params">(Crime crime)</span> </span>&#123;</div><div class="line">    ContentValues values = <span class="keyword">new</span> ContentValues();</div><div class="line">    values.put(Cols.UUID, crime.getId().toString());</div><div class="line">    values.put(Cols.TITLE, crime.getTitle());</div><div class="line">    values.put(Cols.DATE, crime.getDate().getTime());</div><div class="line">    values.put(Cols.SOLVED, crime.isSolved() ? <span class="number">1</span> : <span class="number">0</span>);</div><div class="line">    </div><div class="line">    <span class="keyword">return</span> values;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="4-2-插入和更新记录"><a href="#4-2-插入和更新记录" class="headerlink" title="4.2 插入和更新记录"></a>4.2 插入和更新记录</h2><h3 id="4-2-1-插入记录"><a href="#4-2-1-插入记录" class="headerlink" title="4.2.1 插入记录"></a>4.2.1 插入记录</h3><p>准备好了 ContentValues，就可以进行写入数据了，调用<code>SQLiteDatabase.insert(…)</code>方法即可。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addCrime</span><span class="params">(Crime c)</span> </span>&#123;</div><div class="line">    ContentValues values = getContentValues(c);</div><div class="line">    <span class="comment">/**</span></div><div class="line">     * SQLiteDatabase.insert(String table, String nullColumnHack, ContentValues values)</div><div class="line">     * 第一个参数是表名，第三个参数是键值对</div><div class="line">     * 第二个参数则是当 values 为全空时插入空行</div><div class="line">     * 如果设为 null，则 values 为全空时不插入空行</div><div class="line">     */</div><div class="line">    mDatabase.insert(CrimeTable.NAME, <span class="keyword">null</span>, values);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="4-2-2-更新记录"><a href="#4-2-2-更新记录" class="headerlink" title="4.2.2 更新记录"></a>4.2.2 更新记录</h3><p>更新记录使用的是<code>SQLiteDatabase.update(…)</code>方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateCrime</span><span class="params">(Crime crime)</span> </span>&#123;</div><div class="line">    String uuidString = crime.getId().toString();</div><div class="line">    ContentValues values = getContentValues(crime);</div><div class="line"></div><div class="line">    mDatabase.update(CrimeTable.NAME, values,</div><div class="line">            Cols.UUID + <span class="string">"=?"</span>,</div><div class="line">            <span class="keyword">new</span> String[] &#123;uuidString&#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>update 方法的原型是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">SQLiteDatabase.update(String table, <span class="comment">// 表名</span></div><div class="line">				ContentValues values, <span class="comment">// 键值对</span></div><div class="line">				<span class="comment">// where 后面接的语句，一般是 "columnName = ?"</span></div><div class="line">				String whereClause, </div><div class="line">				<span class="comment">// whereClause 中 ? 代表的语句，可以有多个</span></div><div class="line">				String[] whereArgs</div><div class="line">);</div></pre></td></tr></table></figure>
<p>可以看到，实际上后面两个参数的意思就是 where columnName = columnValue，那么为什么要留出两个参数而不用一个参数解决呢?</p>
<blockquote>
<p>这样做是为了防范 SQL 脚本注入，因为 String 如果本身就带了 SQL 语句，如果不加处理放进数据库执行，就有可能造成灾难性的后果（比如直接 drop 掉所有的表）</p>
</blockquote>
<h1 id="5-读取数据库"><a href="#5-读取数据库" class="headerlink" title="5. 读取数据库"></a>5. 读取数据库</h1><p>读取数据库用到的是 query() 方法，这个方法有许多个重载版本，我们使用下面的版本：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> Cursor <span class="title">query</span><span class="params">(</span></span></div><div class="line">	String table, 			// 表名</div><div class="line">	String[] columns,		// 选中的列名，为 <span class="keyword">null</span> 时选中所有列</div><div class="line">	String where,			// where 语句</div><div class="line">	String[] whereArgs,		// where 语句的参数</div><div class="line">	String groupBy,			// 分组</div><div class="line">	String having,			// 与合计函数一起使用的 having</div><div class="line">	String orderBy,			// 顺序</div><div class="line">	String limit)			<span class="comment">// 限制数量</span></div></pre></td></tr></table></figure>
<p>可以看到返回的是一个 Cursor 对象，下面来探究一下 Cursor 对象</p>
<h2 id="5-1-Cursor-与-CursorWrapper"><a href="#5-1-Cursor-与-CursorWrapper" class="headerlink" title="5.1 Cursor 与 CursorWrapper"></a>5.1 Cursor 与 CursorWrapper</h2><p>Cursor 是个神奇的表数据处理工具，其任务就是封装数据表中的原始字段值。从Cursor获取数据的代码大致如下所示:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">String uuidString = cursor.getString(cursor.getColumnIndex(CrimeTable.Cols.UUID));</div></pre></td></tr></table></figure>
<p>每次要取出一条记录中的一列，都要重复写一次上述代码，所以我们使用 CursorWrapper 建立一个 Cursor 的子类，在其中封装可以转换对象的方法。<br>比如一个类可以这么写：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CrimeCursorWrapper</span> <span class="keyword">extends</span> <span class="title">CursorWrapper</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CrimeCursorWrapper</span><span class="params">(Cursor cursor)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(cursor);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> Crime <span class="title">getCrime</span><span class="params">()</span> </span>&#123;</div><div class="line">    	<span class="comment">//这里是从得到的 CursorWrapper 中取出数据</span></div><div class="line">        String uuidString = getString(getColumnIndex(Cols.UUID));</div><div class="line">        String title = getString(getColumnIndex(Cols.TITLE));</div><div class="line">        <span class="keyword">long</span> date = getLong(getColumnIndex(Cols.DATE));</div><div class="line">        <span class="keyword">int</span> isSolved = getInt(getColumnIndex(Cols.SOLVED));</div><div class="line">        </div><div class="line">		<span class="comment">// 然后生成一个 Model 层对象返回，免去了重复写的繁琐</span></div><div class="line">        Crime crime = <span class="keyword">new</span> Crime(UUID.fromString(uuidString));</div><div class="line">        crime.setTitle(title);</div><div class="line">        crime.setDate(<span class="keyword">new</span> Date(date));</div><div class="line">        crime.setSolved(isSolved != <span class="number">0</span>);</div><div class="line"></div><div class="line">        <span class="keyword">return</span> crime;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="5-2-创建-Model-层对象"><a href="#5-2-创建-Model-层对象" class="headerlink" title="5.2 创建 Model 层对象"></a>5.2 创建 Model 层对象</h2><p>首先封装一个数据库查询方法，返回的是自定义的 CrimeCursorWrapper 对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> CrimeCursorWrapper <span class="title">queryCrimes</span><span class="params">(String whereClause, String[] whereArgs)</span> </span>&#123;</div><div class="line">    Cursor cursor = mDatabase.query(</div><div class="line">            CrimeTable.NAME,</div><div class="line">            <span class="keyword">null</span>, <span class="comment">// Columns -- use null to select all columns</span></div><div class="line">            whereClause,</div><div class="line">            whereArgs,</div><div class="line">            <span class="keyword">null</span>,</div><div class="line">            <span class="keyword">null</span>,</div><div class="line">            <span class="keyword">null</span></div><div class="line">    );</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> CrimeCursorWrapper(cursor);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>再从 CursorWrapper 中获取数据</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 获取所有数据</span></div><div class="line"><span class="function"><span class="keyword">public</span> List&lt;Crime&gt; <span class="title">getCrimes</span><span class="params">()</span> </span>&#123;</div><div class="line">    List&lt;Crime&gt; crimes = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line"></div><div class="line">    CrimeCursorWrapper cursor = queryCrimes(<span class="keyword">null</span>, <span class="keyword">null</span>);</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        cursor.moveToFirst();</div><div class="line">        <span class="keyword">while</span> (!cursor.isAfterLast()) &#123;</div><div class="line">            crimes.add(cursor.getCrime());</div><div class="line">            cursor.moveToNext();</div><div class="line">        &#125;</div><div class="line">    &#125; <span class="keyword">finally</span> &#123;</div><div class="line">        cursor.close();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">return</span> crimes;</div><div class="line">&#125;</div><div class="line"><span class="comment">//获取单个记录</span></div><div class="line"><span class="function"><span class="keyword">public</span> Crime <span class="title">getCrime</span><span class="params">(UUID id)</span> </span>&#123;</div><div class="line">    CrimeCursorWrapper cursor = queryCrimes(</div><div class="line">            Cols.UUID + <span class="string">" = ?"</span>,</div><div class="line">            <span class="keyword">new</span> String[] &#123; id.toString() &#125;</div><div class="line">    );</div><div class="line"></div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        <span class="keyword">if</span> (cursor.getCount() == <span class="number">0</span>) &#123;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        cursor.moveToFirst();</div><div class="line">        <span class="keyword">return</span> cursor.getCrime();</div><div class="line">    &#125; <span class="keyword">finally</span> &#123;</div><div class="line">        cursor.close();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="6-Application-Context-应用上下文"><a href="#6-Application-Context-应用上下文" class="headerlink" title="6 Application Context(应用上下文)"></a>6 Application Context(应用上下文)</h1><p>前面,我们在CrimeLab的构造方法中使用了Application Context。</p>
<pre><code class="java"><span class="function"><span class="keyword">private</span> <span class="title">CrimeLab</span><span class="params">(Context context)</span> </span>{
    mContext = context.getApplicationContext();
    ...
}
&lt;!--￼<span class="number">12</span>--&gt;

```java
<span class="comment">// CrimeFragment.java</span>
<span class="meta">@Override</span>
<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onOptionsItemSelected</span><span class="params">(MenuItem item)</span> </span>{
    <span class="keyword">switch</span> (item.getItemId()) {
        <span class="keyword">case</span> R.id.menu_item_delete_crime:
            CrimeLab.get(getActivity()).deleteCrime(mCrime);
            getActivity().finish();
            <span class="keyword">return</span> <span class="keyword">true</span>;
        <span class="keyword">default</span>:
            <span class="keyword">return</span> <span class="keyword">super</span>.onOptionsItemSelected(item);
    }
}
</code></pre>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016-12-24-cj0ajvoue000a1js6rvhaxbq6/" rel="next" title="Android 常用高级调试技巧">
                <i class="fa fa-chevron-left"></i> Android 常用高级调试技巧
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017-01-11-cj0ajvouw000u1js6vncmebx5/" rel="prev" title="Android编程权威指南（第二版）学习笔记（十五）—— 第15章 隐式 Intent">
                Android编程权威指南（第二版）学习笔记（十五）—— 第15章 隐式 Intent <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://kniost-comment-github.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
                                
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="kniost" />
          <p class="site-author-name" itemprop="name">kniost</p>
           
              <p class="site-description motion-element" itemprop="description">kniost 的成长与疑惑</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-定义-Schema（架构）"><span class="nav-text">1. 定义 Schema（架构）</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-初始创建数据库"><span class="nav-text">2. 初始创建数据库</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-打开数据库"><span class="nav-text">3. 打开数据库</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-写入数据库（插入与更新）"><span class="nav-text">4. 写入数据库（插入与更新）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-使用-ContentValues"><span class="nav-text">4.1 使用 ContentValues</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-插入和更新记录"><span class="nav-text">4.2 插入和更新记录</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-1-插入记录"><span class="nav-text">4.2.1 插入记录</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-2-更新记录"><span class="nav-text">4.2.2 更新记录</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-读取数据库"><span class="nav-text">5. 读取数据库</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-Cursor-与-CursorWrapper"><span class="nav-text">5.1 Cursor 与 CursorWrapper</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-创建-Model-层对象"><span class="nav-text">5.2 创建 Model 层对象</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6-Application-Context-应用上下文"><span class="nav-text">6 Application Context(应用上下文)</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">kniost</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'kniost-comment-github';
      var disqus_identifier = '2017-01-09-cj0ajvouy000y1js6vgfqoi6s/';

      var disqus_title = "Android编程权威指南（第二版）学习笔记（十四）—— 第14章 SQLite 数据库";


      function run_disqus_script(disqus_script) {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');

      
        var disqus_config = function () {
            this.page.url = disqus_url;
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
        };
        run_disqus_script('embed.js');
      

    </script>
  










  
  

  

  

  

  


  

</body>
</html>
